import axios from "axios";
import { Message } from "element-ui";
import router from "@/router/index";

const common = {
  baseUrl: process.env.VUE_APP_URL,
  header: "application/json",
};
// 请求拦截
axios.interceptors.request.use(
  function (config) {
    const token = sessionStorage.getItem("Token");
    const myHeaDers = sessionStorage.getItem("heaDers");
    const prefix = sessionStorage.getItem("prefix");
    if (token) {
      config.headers[myHeaDers] = prefix + " " + token;
    }
    return config;
  },
  function (error) {
    // 处理错误
    return Promise.reject(error);
  }
);
// 响应拦截
axios.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    // 处理错误
    return Promise.reject(error);
  }
);

export function http(url, method, data, IsShow) {
  return new Promise((resolve, reject) => {
    const params = {
      params: data,
    };
    const objData = {
      data: data,
    };
    const res = method === "get" ? params : objData;
    axios({
      url: common.baseUrl + url,
      method: method,
      ...res,
      headers: {
        "Content-Type": common.header,
        // 'Authorization':'Bearer '+sessionStorage.getItem('token')
      },
    })
      .then((res) => {
        if (res.data.code === 200) {
          if (IsShow) {
            Message({
              message: res.data.message,
              type: "success",
              duration: 1000,
            });
          }
        } else {
          Message({
            message: res.data.message,
            type: "error",
            duration: 1000,
          });
        }
        if (res.data.code === 5010) {
          router.push({ path: "/" });
          sessionStorage.clear(); //清除本地缓存
        }
        // 请求接口成功的逻辑
        resolve(res.data);
      })
      .catch((err) => {
        // 请求接口失败的逻辑
        reject(err);
        if (IsShow) {
          Message.error("失败");
        }
      });
  });
}
